package com.sky.sentinel.nacos.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.sky.sentinel.nacos.config.SentinelConfig;
import com.sky.sentinel.nacos.service.ISentinelNacosService;
import org.springframework.stereotype.Service;

@Service
public class SentinelNacosImpl implements ISentinelNacosService {

    @NacosValue(value = "${rule:''}", autoRefreshed = true)
    private String rule;

    @Override
    public String test() {
        SentinelConfig.initFlowQpsRule(rule);
        Entry entry = null;
        // 务必保证finally会被执行
        try {
            // 资源名可使用任意有业务语义的字符串
            entry = SphU.entry("nacos");
            return rule;
        } catch (BlockException e1) {
            return "访问过快，限流降级, 请稍后重试!";
        } finally {
            if (entry != null) {
                entry.exit();
            }
        }
    }
}
